import {
  mall_asyncRoutes,
  constantRoutes,
} from '@/applications/mall/router'
import store from '@/applications/mall/store'
import {
  getLoginType
} from '@/utils/auth'
// import {
//   getLoginType
// } from "@/utils/auth";
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(ruleList, route) {
  if (route.meta) {
    let id = route.meta.id;
    let a_id = route.meta.a_id;
    if (a_id && store.state.common.addons && store.state.common.addons.findIndex(_ => {
        if (Array.isArray(a_id)) {
          return a_id.indexOf(_)>-1
        } else {
          return _ == a_id
        }
      }) == -1) {
      return false
    }
    if (Array.isArray(id)) {
      let a = ruleList.filter(_ => {
        let i = id.findIndex(x => {
          return x == _.level
        })
        return _.resource == 'read' && i > -1
      })
      return a.length > 0
    } else {
      let i = ruleList.findIndex(x => {
        return id == x.level && x.resource == 'read'
      })
      return i > -1
    }
  } else {
    return true
  }
}

function hasPermissionaddons(route) {
  if (route.meta && route.meta.id && route.meta.a_id) {
    let id = route.meta.id;
    let a_id = route.meta.a_id;
    if (a_id && store.state.common.addons && store.state.common.addons.findIndex(_ => {
     if (Array.isArray(a_id)) {
          return a_id.indexOf(_)>-1
        } else {
          return _ == a_id
        }
      }) == -1) {
      return false
    }
    return true
  } else {
    return true
  }
}
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, ruleList) {
  const res = []
  routes.forEach(route => {
    const tmp = {
      ...route
    }
    if (hasPermission(ruleList, tmp)) {
      console.log(tmp)
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, ruleList)
      }
      res.push(tmp)
    }
  })
  return res
}
export function filterAddonsRoutes(routes) {
  const res = []
  routes.forEach(route => {
    const tmp = {
      ...route
    }
    if (hasPermissionaddons(tmp)) {
      if (tmp.children) {
        tmp.children = filterAddonsRoutes(tmp.children)
      }
      res.push(tmp)
    }
  })
  return res
}
const state = {
  routes: [],
  addRoutes: []
}
const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}
const actions = {
  generateRoutes({
    commit
  }, ruleList) {
    return new Promise(resolve => {
      let asyncRoutes = mall_asyncRoutes
      if (getLoginType() == 'mall') {
        var accessedRoutes = filterAsyncRoutes(asyncRoutes, ruleList)
      } else {
        var accessedRoutes = filterAddonsRoutes(asyncRoutes)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
